package com.superbytecode.cloud.common.utils.http;

import com.superbytecode.cloud.common.utils.VerifyUtil;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * All rights Reserved, Designed By www.super-master.com
 *
 * @ProjectName: beacon-cloud
 * @Package: com.superbytecode.cloud.common.utils.context
 * @ClassName: RequestContextUtil
 * @Description: [Request工具类]
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2024/11/13 11:26
 * @Version: V1.0
 * @Copyright: 2024 www.super-master.com Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@UtilityClass
public class HttpRequestUtil {
    /**
     * 获取真实IP地址
     *
     * @return IP地址
     */
    public String obtainRemoteAddress() {
        HttpServletRequest request = obtainRequest();
        // 和运维协商的header，nginx中会在其中存储真实来源ip
        String remoteRealIP = request.getHeader("X-Real-IP");
        // 本地调试不经过nginx，一般返回就是内网ip或本机ip
        return null == remoteRealIP ? request.getRemoteAddr() : remoteRealIP;
    }

    /**
     * 获取请求头信息
     *
     * @param header 请求头
     * @return 请求头信息
     */
    public String obtainReqHeader(String header) {
        return obtainRequest().getHeader(header);
    }

    /**
     * 获取请求信息 <含uri和请求参数>
     * 示例：GET:/api/getUser?id=1
     *
     * @return 请求信息
     */
    public String obtainRequestInfo() {
        HttpServletRequest request = obtainRequest();
        String requestURI = request.getRequestURI();
        String queryString = request.getQueryString();
        queryString = VerifyUtil.isNull(queryString)  ? "" : "?" + queryString;
        return request.getMethod() + ":" + requestURI + queryString;
    }

    /**
     * 获取http对象
     *
     * @return http对象
     */
    public HttpServletRequest obtainRequest() {
        return obtainRequestAttributes().getRequest();
    }

    private ServletRequestAttributes obtainRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }
}